#include "point.h"

int black_piece_idx = 0;
int white_piece_idx = 0;
Point Origin = {185, 340, EMPTY};
//Point Origin = {750, 230, EMPTY};


Point PieceBoard[9] = {
    {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, 
	{IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY},
    {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}
};

Point Corners[4] = {
    {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, 
	{IMG_CENTER_X, IMG_CENTER_Y, EMPTY}, {IMG_CENTER_X, IMG_CENTER_Y, EMPTY}
};

Point WhitePiece[5] = {
    {IMG_CENTER_X, IMG_CENTER_Y, WHITE}, {IMG_CENTER_X, IMG_CENTER_Y, WHITE}, {IMG_CENTER_X, IMG_CENTER_Y, WHITE}, 
	{IMG_CENTER_X, IMG_CENTER_Y, WHITE}, {IMG_CENTER_X, IMG_CENTER_Y, WHITE}
};

Point WhitePieceBuffer[5] = {
    {IMG_CENTER_X, IMG_CENTER_Y, WHITE}, {IMG_CENTER_X, IMG_CENTER_Y, WHITE}, {IMG_CENTER_X, IMG_CENTER_Y, WHITE}, 
	{IMG_CENTER_X, IMG_CENTER_Y, WHITE}, {IMG_CENTER_X, IMG_CENTER_Y, WHITE}
};

Point BlackPiece[5] = {
    {IMG_CENTER_X, IMG_CENTER_Y, BLACK}, {IMG_CENTER_X, IMG_CENTER_Y, BLACK}, {IMG_CENTER_X, IMG_CENTER_Y, BLACK}, 
	{IMG_CENTER_X, IMG_CENTER_Y, BLACK}, {IMG_CENTER_X, IMG_CENTER_Y, BLACK}
};

Point BlackPieceBuffer[5] = {
    {IMG_CENTER_X, IMG_CENTER_Y, BLACK}, {IMG_CENTER_X, IMG_CENTER_Y, BLACK}, {IMG_CENTER_X, IMG_CENTER_Y, BLACK}, 
	{IMG_CENTER_X, IMG_CENTER_Y, BLACK}, {IMG_CENTER_X, IMG_CENTER_Y, BLACK}
};

Point Motor = {IMG_CENTER_X, IMG_CENTER_Y, EMPTY};

Point Middle = {IMG_CENTER_X, IMG_CENTER_Y, EMPTY};

void GroundtoTop (Point *ground)
{
	int x = (CAMERA_HEIGHT * ground->x - MOTOR_HEIGHT * IMG_CENTER_X) / (CAMERA_HEIGHT - MOTOR_HEIGHT);
	int y = (CAMERA_HEIGHT * ground->y - MOTOR_HEIGHT * IMG_CENTER_Y) / (CAMERA_HEIGHT - MOTOR_HEIGHT);
	
	ground->x = x;
	ground->y = y;
}


void ToptoGround (Point *top)
{
	int x = ((CAMERA_HEIGHT - MOTOR_HEIGHT) * top->x + MOTOR_HEIGHT * IMG_CENTER_X) / CAMERA_HEIGHT;
	int y = ((CAMERA_HEIGHT - MOTOR_HEIGHT) * top->y + MOTOR_HEIGHT * IMG_CENTER_Y) / CAMERA_HEIGHT;
	
	top->x = x;
	top->y = y;
}

int IsNear(Point *a, Point *b, int threshold) {
    int dx = a->x - b->x;
    int dy = a->y - b->y;
    return (dx * dx + dy * dy) <= (threshold * threshold); 
}

void UpdatePieceBoardType()
{
    for (int i = 0; i < 9; i++)
    {
        PieceBoard[i].type = EMPTY;

        for (int j = 0; j < 5; j++)
        {
            if (IsNear(&PieceBoard[i], &BlackPieceBuffer[j], 18)) {
                PieceBoard[i].type = BLACK;
                break;
            }
        }

        for (int j = 0; j < 5; j++)
        {
            if (IsNear(&PieceBoard[i], &WhitePieceBuffer[j], 18)) {
                PieceBoard[i].type = WHITE;
                break;
            }
        }
    }
}
